package com.jinyu.admin.service.sys.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.jinyu.admin.service.sys.SysRoleService;
import com.jinyu.dao.entity.sys.SysRole;
import com.jinyu.dao.entity.sys.SysRoleMenu;
import com.jinyu.dao.mapper.sys.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: yangli
 * @Despriction:
 * @Package: com.jinyu.admin.service.sys.impl
 * @Date:Created in 2022/5/5 20:47
 * @Modify By:
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public int insert(SysRole sysRole) {
        // 如果当前会话未登录，这句代码会抛出 `NotLoginException` 异常
        StpUtil.checkLogin();
        String loginId = StpUtil.getLoginIdAsString();
        long id = IdUtil.getSnowflakeNextId();
        sysRole.setId(id);
        sysRole.setCreateUser(loginId);
        sysRole.setUpdateUser(loginId);
        return sysRoleMapper.insert(sysRole);
    }

    @Override
    public int delete(long id) {
        return sysRoleMapper.delete(id);
    }

    @Override
    public int update(SysRole sysRole) {
        return sysRoleMapper.update(sysRole);
    }

    @Override
    public SysRole selectByOneByCode(String roleCode) {
        return sysRoleMapper.selectByOneByCode(roleCode);
    }

    @Transactional
    @Override
    public int distributionRolesToUser(String useCode, String roleCodes) {
        //分割多个角色编码为list
        List<String> roleCodeList = StrUtil.split(roleCodes, ",", true, true);
        List<Map<String, Object>> list = new ArrayList<>();

        for (String roleCode:roleCodeList){
            long id = IdUtil.getSnowflakeNextId();
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("id",id);
            hashMap.put("useCode",useCode);
            hashMap.put("roleCode",roleCode);
            list.add(hashMap);
        }
        //先删除该用户的所有角色,再做批量新增
        int i = sysRoleMapper.deleteByUserCode(useCode);
        return sysRoleMapper.distributionRolesToUser(list);
    }

    @Override
    public List<SysRole> pageList(int offset, int pagesize) {
        return sysRoleMapper.pageList(offset,pagesize);
    }

    @Override
    public List<String> getRoleListByUserCode(String useCode) {
        return sysRoleMapper.getRoleListByUserCode(useCode);
    }

    @Transactional
    @Override
    public int insertRolesPermitToMenu(SysRoleMenu sysRoleMenu) {
        int count = sysRoleMapper.deleteByRoleIdAndMenuId(sysRoleMenu.getRoleId(),sysRoleMenu.getMenuId());
        sysRoleMenu.setId(IdUtil.getSnowflakeNextId());
        return sysRoleMapper.insertRolesPermitToMenu(sysRoleMenu);
    }
}
